package test.LIfeService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import tool.DBUtil;

public class CommunityGroupBuying extends JFrame {
        //groupbuyingID  merchant good price number
    private int groupbuyingID;
    private String merchant;
    private String good;
    private double price;
    private int number;
    private CommunityGroupBuying communityGroupBuying; // 声明对象

    public String toString() {
        return "楼栋编号：" + this.getGroupbuyingID();
    }
    public void setGroupbuyingID(int groupbuyingID) {
        this.groupbuyingID = groupbuyingID;
    }
    public void setMerchant(String merchant) {
        this.merchant = merchant;
    }
    public void setGood(String good) {
        this.good = good;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public int getGroupbuyingID() {
        return groupbuyingID;
    }
    public String getMerchant() {
        return merchant;
    }
    public String getGood() {
        return good;
    }
    public double getPrice() {
        return price;
    }
    public int getNumber() {
        return number;
    }
    public int add(CommunityGroupBuying communityGroupBuying) {
        Connection conn = DBUtil.getConnection();
        String sql = "INSERT INTO communitygroupbuying (groupbuyingID, merchant, good, price, number) VALUES ( ? ,?, ?, ?, ?)";
    try {
         PreparedStatement pstmt = conn.prepareStatement(sql);
         pstmt.setInt(1, communityGroupBuying.getGroupbuyingID());
         pstmt.setString(2, communityGroupBuying.getMerchant());
         pstmt.setString(3, communityGroupBuying.getGood());
         pstmt.setDouble(4, communityGroupBuying.getPrice());
         pstmt.setInt(5, communityGroupBuying.getNumber());
        return pstmt.executeUpdate();
    }
    catch (Exception e) {
         e.printStackTrace();

    }
    DBUtil.closeConnection(conn);
    return 0;
    }

    public int buy(int groupbuyingID) {
        Connection conn = DBUtil.getConnection();
        String sql = "DELETE FROM communitygroupbuying WHERE groupbuyingID = ?";
    try {
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, groupbuyingID);
        return pstmt.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DBUtil.closeConnection(conn);
    }
    return 0;
    }

    public int update(CommunityGroupBuying communityGroupBuying) {
    Connection conn = DBUtil.getConnection();
    String sql = "UPDATE communitygroupbuying SET merchant = ?, good = ?, price = ?, number = ? WHERE groupbuyingID = ?";
    try {
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, communityGroupBuying.getMerchant());
        pstmt.setString(2, communityGroupBuying.getGood());
        pstmt.setDouble(3, communityGroupBuying.getPrice());
        pstmt.setInt(4, communityGroupBuying.getNumber());
        pstmt.setInt(5, communityGroupBuying.getGroupbuyingID());
        int rowsAffected = pstmt.executeUpdate();
        
        if (rowsAffected > 0) {
            // 清除旧的团购数据
            vector.clear();
            
            // 从数据库中查询所有团购信息
            String fetchSql = "SELECT * FROM communitygroupbuying";
            PreparedStatement fetchStmt = conn.prepareStatement(fetchSql);
            ResultSet rs = fetchStmt.executeQuery();
            
            // 将每条团购信息的部分字段放入一个 Vector
            while (rs.next()) {
                Vector<String> row = new Vector<>();
                row.add(String.valueOf(rs.getInt("groupbuyingID")));
                row.add(rs.getString("merchant"));
                row.add(rs.getString("good"));
                row.add(String.valueOf(rs.getDouble("price")));
                row.add(String.valueOf(rs.getInt("number")));
                
                // 把每个 Vector 加入到总的 vector 容器中
                vector.add(row);
            }
            
            // 触发表格数据变更事件，使界面上的表格更新显示
            tm.fireTableDataChanged();
        }
        
        return rowsAffected;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DBUtil.closeConnection(conn);
    }
    return 0;
    }


    JTextField textField1 = new JTextField();//编号
    JTextField textField2 = new JTextField();//商家
    JTextField textField3 = new JTextField();//商品
    JTextField textField4 = new JTextField();//价格
    JTextField textField5 = new JTextField();//人数
    JButton button1 = new JButton("购买");
    JButton button2 = new JButton("添加");
    JButton button3 = new JButton("返回");
    JScrollPane scrollPane;
    AbstractTableModel tm;
    String[] titles = {"编号", "商家", "商品", "价格", "人数"};
    Vector vector = new Vector();

    // 新增查询输入框和按钮
    JTextField queryTextField = new JTextField();
    JButton queryButton = new JButton("查询");

    public CommunityGroupBuying() {
        setTitle("社区团购");
        setBounds(100, 100, 800, 600);
        setLayout(new BorderLayout());

        // 初始化 communityGroupBuying 对象

        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        JPanel panel3 = new JPanel();

        add(panel1, BorderLayout.NORTH);
        add(panel2, BorderLayout.CENTER);
        add(panel3, BorderLayout.SOUTH);

        createTable();
        panel1.add(scrollPane);

        panel2.add(new JLabel("编号："));
        textField1.setColumns(10);
        panel2.add(textField1);
        panel2.add(new JLabel("商家："));
        textField2.setColumns(10);
        panel2.add(textField2);
        panel2.add(textField2);
        panel2.add(new JLabel("商品："));
        textField3.setColumns(10);
        panel2.add(textField3);
        panel2.add(new JLabel("价格："));
        textField4.setColumns(10);
        panel2.add(textField4);
        panel2.add(textField4);
        panel2.add(new JLabel("人数："));
        textField5.setColumns(10);
        panel2.add(textField5);

        panel3.add(new JLabel("查询编号："));
        queryTextField.setColumns(10);
        panel3.add(queryTextField);

        panel3.add(button1);
        button1.addActionListener(e ->{
                buy();
    });
        panel3.add(button2);
        button2.addActionListener(e ->{
            add();
    });
        panel3.add(button3);
        button3.addActionListener(e ->{
               rturn();
    });

        panel3.add(queryButton);
        queryButton.addActionListener(e -> {
            queryById();
        });

}

    private void add() {
        try {
            // 检查输入是否为空
            if (textField1.getText().isEmpty() || textField2.getText().isEmpty() || 
                textField3.getText().isEmpty() || textField4.getText().isEmpty() || 
                textField5.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有字段！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 解析用户输入并设置对象属性
            CommunityGroupBuying communityGroupBuying = new CommunityGroupBuying();
            communityGroupBuying.setGroupbuyingID(Integer.parseInt(textField1.getText()));
            communityGroupBuying.setMerchant(textField2.getText());
            communityGroupBuying.setGood(textField3.getText());
            communityGroupBuying.setPrice(Double.parseDouble(textField4.getText()));
            communityGroupBuying.setNumber(Integer.parseInt(textField5.getText()));

            // 调用添加方法
            if (communityGroupBuying.add(communityGroupBuying) > 0) {
                JOptionPane.showMessageDialog(this, "添加成功！");
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！");
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "输入格式错误，请检查编号、价格和人数是否为有效数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
        update();
    }

    private void buy() {
        int id = Integer.parseInt(textField1.getText());
        if (buy(id) > 0) { // 使用新的 delete 函数
            JOptionPane.showMessageDialog(this, "购买成功！");
        } else {
            JOptionPane.showMessageDialog(this, "购买失败！");
        }
        update();
    }

    private void update() {
        int id = Integer.parseInt(textField1.getText());
        CommunityGroupBuying communityGroupBuying = new CommunityGroupBuying();
        communityGroupBuying.setGroupbuyingID(id);
        communityGroupBuying.setMerchant(textField2.getText());
        communityGroupBuying.setGood(textField3.getText());
        communityGroupBuying.setPrice(Double.parseDouble(textField4.getText()));
        communityGroupBuying.setNumber(Integer.parseInt(textField5.getText()));
        fetchDataFromDatabase(); // 更新后重新加载数据
    }

    private void createTable() {
        JTable table;
        tm = new AbstractTableModel() {
            public int getRowCount() {
                return vector.size();
            }

            @Override
            public int getColumnCount() {
                return titles.length;
            }

            @Override
            public String getColumnName(int column) {
                return titles[column];
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                if (!vector.isEmpty()) {
                    return ((Vector) vector.get(rowIndex)).get(columnIndex);
                } else {
                    return null;
                }
            }
        };
        table = new JTable(tm);
        scrollPane = new JScrollPane(table);
        scrollPane.setBounds(0, 0, 540, 150);
    }

    // 新增函数：从数据库中取出数据
    private void fetchDataFromDatabase() {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM communitygroupbuying";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            vector.clear(); // 清空当前数据
            while (rs.next()) {
                Vector row = new Vector();
                row.add(rs.getInt("groupbuyingID"));
                row.add(rs.getString("merchant"));
                row.add(rs.getString("good"));
                row.add(rs.getDouble("price"));
                row.add(rs.getInt("number"));
                vector.add(row);
            }
            tm.fireTableDataChanged(); // 通知表格模型数据已更改
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
        }
    }

    // 新增查询功能
    private void queryById() {
        String queryId = queryTextField.getText().trim();
        if (queryId.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入编号！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM communitygroupbuying WHERE groupbuyingID = ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, Integer.parseInt(queryId));
            ResultSet rs = pstmt.executeQuery();
            vector.clear();
            while (rs.next()) {
                Vector row = new Vector();
                row.add(rs.getInt("groupbuyingID"));
                row.add(rs.getString("merchant"));
                row.add(rs.getString("good"));
                row.add(rs.getDouble("price"));
                row.add(rs.getInt("number"));
                vector.add(row);
            }
            tm.fireTableDataChanged();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询失败！", "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.closeConnection(conn);
        }
    }

    // 新增重置功能
    private void resetData() {
        fetchDataFromDatabase();
    }

    //退出到主界面，不退出程序
    private void rturn() {
        button3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                LIFeService lifeService = new LIFeService(); // 创建 LIFeService 实例
                lifeService.setVisible(true); // 显示 LIFeService 界面
            }
        });

    }








    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            CommunityGroupBuying communityGroupBuying = new CommunityGroupBuying();
            communityGroupBuying.setVisible(true);
            communityGroupBuying.fetchDataFromDatabase(); // 初始化时从数据库加载数据
        });
    }
}